var CONTEXT_PATH = "/enterprise";

window.alert = function(message) {
	if(!$(".alert-box").length) {
		$("body").append(
			'<div class="modal alert-box" tabindex="-1" role="dialog">'+
				'<div class="modal-dialog" role="document">'+
				'<div class="modal-content">'+
					'<div class="modal-header">'+
						'<h5 class="modal-title">提示</h5>'+
						'<button type="button" class="close" data-dismiss="modal" aria-label="Close">'+
							'<span aria-hidden="true">&times;</span>'+
						'</button>'+
					'</div>'+
					'<div class="modal-body">'+
						'<p></p>'+
					'</div>'+
					'<div class="modal-footer">'+
						'<button type="button" class="btn btn-secondary" data-dismiss="modal">确定</button>'+
					'</div>'+
					'</div>'+
				'</div>'+
			'</div>'
		);
	}

    var h = $(".alert-box").height();
	var y = h / 2 - 100;
	if(h > 600) y -= 100;
    $(".alert-box .modal-dialog").css("margin", (y < 0 ? 0 : y) + "px auto");
	
	$(".alert-box .modal-body p").text(message);
	$(".alert-box").modal("show");
}

//var arr=[
//            {name:"baidu",href:"http://www.baidu.com"},
//            {name:"baidu",href:"http://www.baidu.com"},
//            {name:"baidu",href:"http://www.baidu.com"},
//            {name:"baidu",href:"http://www.baidu.com"},
//
//        ];
//
//
//        document.getElementById("btn").onclick=function(){
//            var str="<table border='1'>";
//            for(var i=0;i<arr.length;i++){
//                str+="<tr>"+"<td>"+arr[i].name+"</td>"+"<td>"+"<a href="+arr[i].href+">"+arr[i].name+"</a>"+"</td>"
//            }
//            str+="</table>";
//            document.getElementById("box").innerHTML=str;
//        }


$(function(){
	$("form").submit(check_data);
	$("input").focus(clear_error);
});

function check_data() {
	var pwd1 = $("#password").val();
	var pwd2 = $("#confirm-password").val();
	if(pwd1 != pwd2) {
		$("#confirm-password").addClass("is-invalid");
		return false;
	}
	return true;
}


$(function(){
    $("#submitLog").click(submitSeLog);
    $("#submitDraft").click(submitSeLogDraft);
    $("#increate").click(increateDanger);
    $("#submitPic").click(sumbitImage);
});

function sumbitImage() {


     var fd = new FormData();
        fd.append("file",$("#photo").get(0).files[0])
        $.ajax({
            type: "post",
            url: CONTEXT_PATH+"/upPic",
            data: fd,
            cache: false,
            processData: false,
            contentType: false,
            success (res) {

                console.log(res);

                            var str="<table border='1'>";
                            for(var i=0;i<res.length;i++){
    //                            str+="<tr>"+"<td>"+arr[i].name+"</td>"+"<td>"+"<a href="+arr[i].href+">"+arr[i].name+"</a>"+"</td>"
    //                             <table>
    //                                            <tr>
    //                                                <td>
    //                                                    图片上传
    //                                                    <input type="file" id="photo" onchange="upPic()">
    //                                                    <img src="" alt="" id="img" width="135px">
    //                                                    <input type="hidden" id="photoPath">
    //                                                    <input type="button" value="下载图片" onclick="downloadPhoto()">
    //                                                </td>
    //                                            </tr>
    //                                        </table>
                                str+="<tr>"+"<td>"+"<img src="+CONTEXT_PATH+"/showImg?path="+res[i].pictureAddress+"+ id="+i+" width=135px>"+"</td>"
                                str+="<tr>"+"<td>"+"<a th:href=@{|/log/detail/${"+res[i].id+"}|}>"+ "</a>"+"</td>"
                                str+="<tr>"+"<td>"+"<a type=button class='btn btn-info text-white form-control' id=deletePic href="+CONTEXT_PATH+"/deleteImage/"+res[i].id+" >删除</a>"+"</td>"
                                str+="<tr>"+"<td>"+"<button type=button class='btn btn-info text-white form-control' >下载</button>"+"</td>"



                            }
                            str+="</table>";

                            document.getElementById("box").innerHTML=str;

            }
        })

}

function submitSeLog() {

    var checkTime=$("#checkTime").val();
    var chargePhone=$("#chargePhone").val();
    var logPhone=$("#logPhone").val();
    var inspector=$("#inspector").val();
    var weather=$("#weather").val();
    var temperature=$("#temperature").val();
    var personDuty=$("#personDuty").val();
    var device=$("#device").val();
    var business=$("#business").val();
    var education=$("#education").val();
    var food=$("#food").val();
    var other=$("#other").val();



    $.post(
        CONTEXT_PATH + "/add-selog",
        {"checkTime":checkTime,"draft":0,"chargePhone":chargePhone,"logPhone":logPhone,"inspector":inspector,
        "weather":weather,"temperature":temperature,"personDuty":personDuty,"device":device,"business":business,"education":food,"food":education,"other":other,"type":1},

        function(data) {
               data = $.parseJSON(data);
                // 在提示框中显示返回消息
                $("#hintBody").text(data.addSeLogInfo);
                // 显示提示框
                $("#hintModal").modal("show");
                // 2秒后,自动隐藏提示框
                setTimeout(function(){
                    $("#hintModal").modal("hide");
                    // 刷新页面
                    if(data.code == 0) {
                        //window.location.reload();
                        window.location.href = CONTEXT_PATH+"/enterpriseHome";
                    }
                }, 5000);




                console.log(data)

        }
    );

}

function submitSeLogDraft() {

    var checkTime=$("#checkTime").val();
    var chargePhone=$("#chargePhone").val();
    var logPhone=$("#logPhone").val();
    var inspector=$("#inspector").val();
    var weather=$("#weather").val();
    var temperature=$("#temperature").val();
    var personDuty=$("#personDuty").val();
    var device=$("#device").val();
    var business=$("#business").val();
    var education=$("#education").val();
    var food=$("#food").val();
    var other=$("#other").val();


    $.post(
        CONTEXT_PATH + "/add-selog",
        {"checkTime":checkTime,"draft":1,"chargePhone":chargePhone,"logPhone":logPhone,"inspector":inspector,
        "weather":weather,"temperature":temperature,"personDuty":personDuty,"device":device,"business":business,"education":food,"food":education,"other":other,"type":1},

        function(data) {
            data = $.parseJSON(data);

            console.log(data)

            // 在提示框中显示返回消息
            $("#hintBody").text(data.addSeLogInfo);
            // 显示提示框
            $("#hintModal").modal("show");
            // 2秒后,自动隐藏提示框
            setTimeout(function(){
                $("#hintModal").modal("hide");
                // 刷新页面
                if(data.code == 0) {
                    //window.location.reload();
                    window.location.href = CONTEXT_PATH+"/enterpriseHome";
                }
            }, 2000);









            //var t=setTimeout("alert('"+data+"')",2000)
            //window.location.href = CONTEXT_PATH+"/enterpriseHome";




        }
    );

}



//$("#upload").on("click",function () {
//           var fileObj = document.getElementById("file").files[0];
//           var form = new FormData();
//           form.append("file",fileObj);
//           var xhr = new XMLHttpRequest();
//           xhr.open("post","http://localhost:8080/enterprise/upload",true);
//           xhr.onload = function(event){
//               alert(event.currentTarget.responseText);
//               window.location.href = window.location.href;
//           };
//           xhr.send(form);
//});
//
//
//var fileList = this.files;
//		for(var i = 0; i < fileList.length; i++) {
//			var imgSrcI = getObjectURL(fileList[i]);
//			imgName.push(fileList[i].name);
//			imgSrc.push(imgSrcI);
//			imgFile.push(fileList[i]);
//		}
//
//function getObjectURL(file) {
//	var url = null ;
//	if (window.createObjectURL!=undefined) { // basic
//		url = window.createObjectURL(file) ;
//	} else if (window.URL!=undefined) { // mozilla(firefox)
//		url = window.URL.createObjectURL(file) ;
//	} else if (window.webkitURL!=undefined) { // webkit or chrome
//		url = window.webkitURL.createObjectURL(file) ;
//	}
//	return url ;
//}
//
//$('#upload').on('change',function(){
//      if(imgSrc.length==4){
//        return alert("最多只能上传4张图片");
//    }
//    var imgSize = this.files[0].size;  //b
//    if(imgSize>1024*1024*1){//1M
//        return alert("上传图片不能超过1M");
//    }
//    if(this.files[0].type != 'image/png' && this.files[0].type != 'image/jpeg' && this.files[0].type != 'image/gif'){
//        return alert("图片上传格式不正确");
//    }
//})
//
//function addNewContent(obj) {
//	$(obj).html("");
//	for(var a = 0; a < imgSrc.length; a++) {
//		var oldBox = $(obj).html();
//		$(obj).html(oldBox + '<li class="content-img-list-item"><img src="'+imgSrc[a]+'" alt=""><a index="'+a+'" class="hide delete-btn"><i class="ico-delete"></i></a></li>');
//	}
//}
//
//
//// 多张图片
//    var arr=[]
//    $('#picture').on('change', function(){
//        var imgFiles = $(this)[0].files
//        console.log("多张图片",imgFiles)
//        var formData =  new FormData();
//        for (i=0;i<imgFiles.length;i++){
//            filePath = imgFiles[i].name;
//            fileFormat = filePath.split('.')[1].toLowerCase()
//            if( !fileFormat.match(/png|jpg|jpeg/) ) {
//                alert('上传错误,文件格式必须为：png/jpg/jpeg')
//                return
//            }
//            formData.append('upfile', $(this)[0].files[i]); //添加图片信息的参数
//            var preview = document.getElementById("previewImg")
//            var div = document.createElement('div')
//            var a = document.createElement('a')
//            var img = document.createElement('img')
//            $.ajax({
//                url: "/upload",
//                type: "post",
//                dataType: "json",
//                cache: false,
//                mimeType: "multipart/form-data",
//                data: formData,
//                processData: false,// 不处理数据
//                contentType: false, // 不设置内容类型
//                async:false,
//                success:function (result){
//                    arr[i]=result
//                    img.width = 150
//                    img.src = arr[i]
//                    preview.appendChild(div)
//                    div.appendChild(a)
//                    div.appendChild(img)
//                    $('#s_imgpath').val(arr)
//                    //这儿  把我返回的值， 插入到那个数组里面 s_imgpath[]
//                }
//            });
//        }
//    })
//    //控制"按钮"显示与隐藏
//    $("#previewImg").off("mouseenter","div").on("mouseenter","div",function(){
//        var that=this;
//        var dom=$(that).children("a");
//        dom.removeClass("hide");
//        dom.addClass("show");
//        //为点击事件解绑，防止重复执行
//        dom.off("click");
//        dom.on("click",function(){
//            //删除当前图片
//            dom.parent().remove();
//            var imgsrc = dom.parent().children("img")[0].src   //当前图片src
//            arr.removeByValue(imgsrc);             //从数组中移除当前图片
//            $('#s_imgpath').val(arr)               //给input重新赋值
//        });
//    }).off("mouseleave","div").on("mouseleave","div",function(){
//        var that=this;
//        $(that).children("a").addClass("hide");
//    })
//    Array.prototype.removeByValue = function(val) {    //删除数组中元素
//      for(var i=0; i<this.length; i++) {
//        if(this[i] == val) {
//          this.splice(i, 1);
//          break;
//        }
//      }
//    }


function upPic() {
    var fd = new FormData();
    fd.append("file",$("#photo").get(0).files[0])
    $.ajax({
        type: "post",
        url: CONTEXT_PATH+"/upPic",
        data: fd,
        cache: false,
        processData: false,
        contentType: false,
        success (res) {

            console.log(res);


//            var arr=[
//                        {name:"baidu",href:"http://www.baidu.com"},
//                        {name:"baidu",href:"http://www.baidu.com"},
//                        {name:"baidu",href:"http://www.baidu.com"},
//                        {name:"baidu",href:"http://www.baidu.com"},
//
//                    ];
//                    <a th:href="@{|/log/detail/${map.post.id}|}">
//                        <img th:src="${map.post.checkTime}" class="mr-4 rounded-circle" alt="标识"
//                             style="width:50px;height:50px;">
//                    </a>



                        var str="<table border='1'>";
                        for(var i=0;i<res.length;i++){
//                            str+="<tr>"+"<td>"+arr[i].name+"</td>"+"<td>"+"<a href="+arr[i].href+">"+arr[i].name+"</a>"+"</td>"
//                             <table>
//                                            <tr>
//                                                <td>
//                                                    图片上传
//                                                    <input type="file" id="photo" onchange="upPic()">
//                                                    <img src="" alt="" id="img" width="135px">
//                                                    <input type="hidden" id="photoPath">
//                                                    <input type="button" value="下载图片" onclick="downloadPhoto()">
//                                                </td>
//                                            </tr>
//                                        </table>
                            str+="<tr>"+"<td>"+"<img src="+CONTEXT_PATH+"/showImg?path="+res[i].pictureAddress+"+ id="+i+" width=135px>"+"</td>"
                            str+="<tr>"+"<td>"+"<a th:href=@{|/log/detail/${"+res[i].id+"}|}>"+ "</a>"+"</td>"
                            str+="<tr>"+"<td>"+"<a type=button class='btn btn-info text-white form-control' id=deletePic href="+CONTEXT_PATH+"/deleteImage/"+res[i].id+" >删除</a>"+"</td>"
                            str+="<tr>"+"<td>"+"<button type=button class='btn btn-info text-white form-control' >下载</button>"+"</td>"



                        }
                        str+="</table>";

                        document.getElementById("box").innerHTML=str;






//            // 赋值给img的src属性 实现预览图片
//            $("#img").prop("src",CONTEXT_PATH+"/showImg?path="+res[7].pictureAddress+"")
//            // 将图片路径赋值给一个属性
//            $("#photoPath").val(res[7].pictureAddress)
//
//
//            var html="";
//            for(var i=0;i<1;i++){
//                console.log(i)
////                html+=  "<tr>"+
////                            "<td>"+res[i].pictureInfo+"</td>"+
//////                "<img src="+res[2].pictureAddress+" id=img"+i+"width=135px">+
////                            "<td>"+res[10].pictureAddress+"</td>"+
////                        "</tr>"
//
//
//
//            }
//            $("#content").html(html);
//            console.log(html);
//
//
//             $("body").append(
//
//
//             );
        }
    })
}



function downloadPhoto() {
   location = "/user/download?path="+$("#photoPath").val();
}










